package com.cloudcc.mobile.dao.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.cloudcc.cloudframe.net.RequestListener;
import com.cloudcc.cloudframe.net.async.JsonObjectRequest;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.dao.BaseEngine;
import com.cloudcc.mobile.dao.ImageEngine;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.ManyImage;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.loopj.android.http.RequestParams;

public class ImageEngineImpl extends BaseEngine implements ImageEngine {

	@Override
	public void uploadImage(List<AddImageInfo> images,RequestListener li) {
		final List<ManyImage> imglist = new ArrayList<ManyImage>();
		for (int i = 0; i < images.size(); i++) {
			File file = new File(images.get(i).getImagePath());
			if (!file.exists()) {// 如果不存在就放弃
				continue;
			}
			ManyImage image = new ManyImage();
			image.setImgName(images.get(i).getImagePath());
			image.setAddress("");
			image.setImgHeight("");
			image.setImgWidth("");
			image.setImgId("");
			image.setImgType("jpg");
			imglist.add(image);
		}
		final String[] imagepaths = new String[imglist.size()];

		for (int i = 0; i < images.size(); i++) {
			imagepaths[i] = images.get(i).getImagePath();
			ManyImage image = new ManyImage();
			image.setImgName(images.get(i).getImagePath());
			image.setAddress("");
			image.setImgHeight("");
			image.setImgWidth("");
			image.setImgId("");
			image.setImgType("jpg");
			imglist.add(image);
		}
		String paramImages = GsonUtil.Object2Json(imglist);
		String decode1 = paramImages.replaceAll(" ", "%20");
		String decode = decode1;
		try {
			decode = URLEncoder.encode(decode1, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		RequestParams params = new RequestParams();
		for (int i = 0; i < imagepaths.length; i++) {
			try {
				File file = new File(imagepaths[i]);
				params.put("file" + (i + 1), file, file.getName());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		String host = StringUtils.replace(UrlManager.getInterfaceUrl(),
				"https://", "http://");

		final String url = host + "?serviceName=uploadImgMany&data=" + decode
				+ "&binding=" + RunTimeManager.getInstance().getServerBinding();
		JsonObjectRequest request =new JsonObjectRequest();
		request.setRequestListener(li);
		sendPost(url, params, request);
	}

}
